<template>
  <ul class="alp-list">
     <li
       :ref="item"
       v-for="item of letters"
       class="item"
       :key="item"
       @click="letterClick"
       @touchstart="handleTouchStart"
       @touchmove="handleTouchMove"
       @touchend="handleTouchEnd"
       >{{item}}</li>
  </ul>
</template>

<script>
export default ({
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      // 节流 进行性能优化
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        // 节流设置
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // A 按钮距离顶部的高度 系统api 多次调用耗费性能
          // this.startY = this.$refs['A'][0].offsetTop
          // 修改如下 通过生命周期hooks进行调用，其余通过data访问
          const startY = this.startY
          // 79是header的高度 touchY是当前鼠标相对HTML的高度
          // - 79 是相对list组件的高度
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 8)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    },
    letterClick: function (e) {
      this.$emit('change', e.target.innerText)
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  }
})
</script>

<style lang="stylus" scoped>
  @import '~@/assets/varibles.styl'
  .alp-list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0rem
    bottom: 0rem
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
